package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"send-id-num/internal/repository"
	"send-id-num/pkg/http"
)

type SignInReq struct {
	QQNum           int    `json:"qqNum" binding:"required"`
	Password        string `json:"password" binding:"required"`
	ConfirmPassword string `json:"confirmPassword" binding:"required"`
}

func SignIn(c *gin.Context) {
	var req SignInReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode(err.Error()))
		return
	}
	if req.Password != req.ConfirmPassword {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("两次密码不一致！"))
		return
	}
	// 校验信息
	user, err := repository.GetUserInfoByQQNum(req.QQNum)
	if err == gorm.ErrRecordNotFound || user.Id == 0 {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("未找到该账号信息，请联系管理员！"))
		return
	}
	if err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("GetUserInfoByQQNum err "+err.Error()))
		return
	}
	if user.Password != "" {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("该账号已设置过密码，如有忘记联系管理！"))
		return
	}
	if err = user.Id.SetPassword(req.Password); err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("set password err"+err.Error()))
		return
	}
	c.JSON(http.StatusOK, http.SuccessRes())
}
